<?php
/**
 * Created by PhpStorm.
 * User: lyh
 * Date: 2017/4/15
 * Time: 20:27
 */
namespace Admin\Controller;

class PostController extends CommonController{
    public function index(){
        $area_id=I('area_id','0');//默认不传值为1
        $summary=I('summary','');
        if(!empty($area_id)){
            $map['pid']=$area_id;
        }

        $map['summary']=array('like','%'.$summary.'%');
        $Model=M('Areapost');
        $userModel=M('Userdetail');
        $areaModel=M('Areaassociation');
        $count= $Model->count();// 查询满足要求的总记录数
        $Page = new \Think\Page($count,20);// 实例化分页类 传入总记录数和每页显示的记录数(25)
        $show = $Page->show();// 分页显示输出// 进行分页数据查询 注意limit方法的参数要使用Page类的属性
        $post_info=$Model->order('time desc')->where($map)->limit($Page->firstRow.','.$Page->listRows)->field('id,pid,commentcount,userid,title,time,userid,summary')->select();
        $area_info=$areaModel->field('id,title')->select();
        foreach($post_info as $key=>$value){
            $post_info[$key]['username']=$userModel->where('userid='.'"'.$value['userid'].'"')->getField('username');
            $post_info[$key]['area']=$areaModel->where(array('id'=>$value['pid']))->getField('title');
            unset($post_info[$key]['userid']);
        }
        $this->assign('area_id',$area_id);
        $this->assign('area_info',$area_info);
        $this->assign('post_info',$post_info);// 赋值数据集
        $this->assign('page',$show);// 赋值分页输出
        $this->display();
    }

    public function detail(){
        $userModel=M('Userdetail');
        $id=$_GET['id'];
        $post_info=M('Areapost')->where('id='.$id)->field('title,content')->find();
        $comment_info=M('Areacomment')->where('pid='.$id)->field('id,userid,content,time')->select();
        foreach($comment_info as $key=>$value){
            $user_info=$userModel->where('userid='.$value['userid'])->field('username,headurl')->find();
            $comment_info[$key]['username']=$user_info['username'];
            $comment_info[$key]['headurl']=$user_info['headurl'];
            unset($comment_info[$key]['userid']);
        }
        $this->assign('post_info',$post_info);
        $this->assign('comment_info',$comment_info);
        $this->display();

    }

    public function del_comment(){
        $id=$_GET['id'];
        $post_id=M('Areacomment')->where('id='.$id)->getField('pid');;
        $result=M('Areacomment')->where('id='.$id)->delete();
        if($result){
            M('Areapost')->where('id='.$post_id)->setDec('commentcount',1);
            $this->ajaxReturn(1);
        }else{
            $this->ajaxReturn(2);
        }
    }
}